package cn.liangcaomei.educenter.controller;

import cn.liangcaomei.educenter.utils.ConstantWxUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;

@Controller     //注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxApiController {

    //1 生成微信二维码
    @GetMapping("login")
    public String getWxCode() {

        //2 拿着code请求 微信的固定地址，得到两个值access_token和openid
        // 微信开放平台授权baseUrl, %s 相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEncode编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置 %s 里面值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
        );
        //重定向到请求微信地址里面
        return "redirect:" + url;
    }
}
